const args = require('minimist')(process.argv.slice(2))
const {build} = require('esbuild')  // 引入esbuild，使用esbuild构建
const {resolve} = require('path');

const target = args._[0] || 'reactivity';
const format = args.f || 'global';

// 设置package.json的路径
const pkg = require(resolve(__dirname, `../packages/${target}/package.json`));

/**
 * life 立即执行函数  (function(){}())
 * cjs node中的模块 module.exports
 * esm 浏览器中esModule模块 import
 */
const outputFormat = format.startsWith('global') ? 'iife' : format === 'cjs' ? 'cjs' : 'esm'

const outfile = resolve(__dirname, `../packages/${target}/dist/${target}.${format}.js`)

process.on('unhandledRejection', (reason, p) => {
    console.log('报错Unhandled Rejection at: Promise', p, 'reason:', reason);
    // application specific logging, throwing an error, or other logic here
  });

build({
    entryPoints: [resolve(__dirname,`../packages/${target}/src/index.ts`)],
    outfile: outfile,
    bundle: true, // 是否把所有的包全部打到一起
    sourcemap: true,
    format: outputFormat,  // 输出的格式，nodejs   浏览器esm  还是cjs
    globalName: pkg.buildOptions?.name,  // 打包的全局名字
    platform: format === 'cjs' ? 'node' : 'browser', // 平台
    watch: { // 监控文件变化
        onRebuild(error) {
            if (!error) {console.log('rebuild...')}
        }
    }
}).then(() => {
    console.log('watching~~~')
})